package com.senseauto.ah8mediacodec.utils;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * 2024-4-12
 * MediaCodec 编码视频，用的byte[]次数多，换成对象池的方式改善 内存和cpu占用
 * 可以在MediaCodec录像时降低10%左右的cpu占用
 */
public class ByteBufferPool {


    //原先的写法，复用的byte[]大小都是固定的 1920*1088*1.5的大小
    private List<ByteBuffer> bufferPool;
    private int bufferSize;
    public static ByteBufferPool instance;
    static {
        synchronized (ByteBufferPool.class) {
            instance = new ByteBufferPool((int) (  1920*1088 * 1.5), 16);
        }
    }

    public static ByteBufferPool getInstance() {
        return instance;
    }

    private ByteBufferPool(int bufferSize, int initialBufferCount) {
        this.bufferSize = bufferSize;
        bufferPool = new ArrayList<>(initialBufferCount);
        for (int i = 0; i < initialBufferCount; i++) {
            bufferPool.add(ByteBuffer.allocate(bufferSize));
        }
    }

    public ByteBuffer getBuffer() {
        ByteBuffer buffer;
        synchronized (bufferPool) {
            if (bufferPool.isEmpty()) {
                buffer = ByteBuffer.allocate(bufferSize);
            } else {
                buffer = bufferPool.remove(bufferPool.size() - 1);
            }
        }
        return buffer;
    }

    public void returnBuffer(ByteBuffer buffer) {
        if (buffer.capacity() != bufferSize) {
            // 确保缓冲区大小匹配
            throw new IllegalArgumentException("Buffer has incorrect capacity");
        }
        synchronized (bufferPool) {
            buffer.clear(); // 清空缓冲区，以便重用
            bufferPool.add(buffer);
        }
    }
}
